import React from 'react';
import Image from 'next/image';
import { format, fromUnixTime } from 'date-fns';
import MarkdownIt from 'markdown-it';
import { CopyIcon, RefreshIcon, MicIcon } from './Icons';

interface ChatReplyProps {
  data: {
    icon: string;
    content: string;
    prompt?: string;
    created_at?: number;
  };
  onRegen: (prompt: string) => void;
  readOnly: boolean;
}

// @ts-expect-error: markdown-it 类型定义问题
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
});

const ChatReply: React.FC<ChatReplyProps> = ({ data, onRegen, readOnly }) => {
  const defaultAvatar = 'https://gravatar.com/avatar/a21644f154385c78278455e9404b9a52?s=400&d=robohash&r=x';
  const timestamp = data.created_at ? format(fromUnixTime(data.created_at), 'yyyy-MM-dd HH:mm:ss') : '';
  
  const handleCopy = () => {
    navigator.clipboard.writeText(data.content);
  };
  
  const handleRegenerate = () => {
    if (data.prompt) {
      onRegen(data.prompt);
    }
  };

  return (
    <>
      {timestamp && <div className="chat-timestamp">{timestamp}</div>}
      <div className="chat-reply">
        <div className="chat-reply-inner">
          <Image src={data.icon || defaultAvatar} alt="AI" width={32} height={32} className="chat-reply-avatar" />
          <div className="chat-reply-bubble">
            <div className="markdown-body" dangerouslySetInnerHTML={{ __html: md.render(data.content) }} />
            {!readOnly && (
              <div className="chat-reply-footer">
                <div className="chat-reply-actions">
                  <button onClick={handleCopy} title="复制">
                    <CopyIcon width={16} height={16} />
                  </button>
                  <button onClick={handleRegenerate} title="重新生成">
                    <RefreshIcon width={16} height={16} />
                  </button>
                  <button title="朗读">
                    <MicIcon width={16} height={16} />
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default ChatReply; 